package org.oschina.api.user.bar.service;

import java.util.ArrayList;
import java.util.List;
import org.oschina.Constants;
import org.oschina.Message;
import org.oschina.Module;
import org.oschina.ResultUtil;
import org.oschina.api.BaseService;
import org.oschina.bean.Result;
import org.oschina.security.annotation.Require;
import org.oschina.api.index.service.IndexService;
import org.oschina.api.user.bar.dao.UserBarRoleDAO;
import org.oschina.api.user.bar.vo.UserBarRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserBarRoleService extends BaseService {

	@Autowired
	private UserBarRoleDAO barRoleDAO;
	@Autowired
	private UserBarService barService;
	@Autowired
	private IndexService indexService;
	
	/**
	 * 更新
	 * @param role
	 * @param barRoles
	 * @return
	 */
	@Require(authorization=Module.MODULE_9)
	public Result update(int role,int barRoles[])
	{
		List<UserBarRole> args=new ArrayList<UserBarRole>();
		for(int barRole:barRoles)
		{
			if(barService._findVoById(barRole)==null)
				return ResultUtil.getFailure(Message.ERROR_DATA_ERROR);
			
			UserBarRole temp=new UserBarRole();
			temp.setId(_getIndex());
			temp.setBar(barRole);
			temp.setRole(role);
			args.add(temp);
		}
		barRoleDAO.update(role, args);
		
		return ResultUtil.getSuccess(Message.UPDATE_SUCCESS);
	}
	
	/**
	 * 根据bar删除
	 * @param bar
	 * @return
	 */
	public int _removeByBar(int bar)
	{
		return barRoleDAO.removeByBar(bar);
	}
	
	private int _getIndex()
	{
		return indexService.getMajorById(Constants.INDEX_USER_BAR_ROLE);
	}
}